package com.atgugu.springcloud.service.impl;

import com.atgugu.springcloud.dao.OrderDao;
import com.atgugu.springcloud.domain.Order;
import com.atgugu.springcloud.service.AccountService;
import com.atgugu.springcloud.service.OrderService;
import com.atgugu.springcloud.service.StorageService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

import javax.annotation.Resource;

/**
 * @author ZhangXinWang
 * @date 2023/1/7 19:34
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderDao orderDao;
    @Resource
    private StorageService storageService;
    @Resource
    private AccountService accountService;

    @Override
    @GlobalTransactional(name = "fsp-create-order",rollbackFor = Exception.class)
    public void create(Order order) {
        StopWatch stopWatch = new StopWatch("创建订单");
        stopWatch.start("新建订单");
        orderDao.create(order);
        stopWatch.stop();
        stopWatch.start("订单微服务开始调用库存,做扣减");
        storageService.decrease(order.getProductId(), order.getCount());
        stopWatch.stop();
        stopWatch.start("账户微服务开始调用账户,做扣减");
        accountService.decrease(order.getUserId(), order.getMoney());
        stopWatch.stop();
        stopWatch.start("修改订单状态,0->1表示已完成");
        orderDao.update(order.getId(), 1);
        stopWatch.stop();
        log.info(stopWatch.prettyPrint());
    }

}
